package com.mt.common.exception.handler;

import com.alibaba.fastjson.JSONObject;
import com.mt.common.utils.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @Author: plover
 * @Date: 2020/07/18/4:02 下午
 * @Description:
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.mt"})
public class AppGlobalExceptionHandler {

    /**
     * 处理所有不可知的异常
     */
    @ExceptionHandler(Exception.class)
    public JSONObject handleException(Throwable e){
        // 打印堆栈信息
        String stackTrace = ThrowableUtil.getStackTrace(e);
        log.error(stackTrace);
        return buildResponseEntity(ApiError.error(stackTrace));
    }

    /**
     * 统一返回
     */
    private JSONObject buildResponseEntity(ApiError apiError) {
        JSONObject result = new JSONObject();
        result.put("code", apiError.getStatus());
        result.put("message", "系统异常，请联系管理员解决");
        result.put("data", apiError.getMessage());
        return result;
    }
}
